
import java.io.*;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.mail.Flags.Flag;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.FlagTerm;
import javax.swing.table.DefaultTableModel;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
/**
 *
 * @author lochuynh
 */
public class project_1 extends javax.swing.JFrame {

    /**
     * Creates new form project_1
     */
    private String keyPath = "";
    public Message messages[];
    String ecrptScheme = StringEncrypter.DES_ENCRYPTION_SCHEME;
    String content;
    String key;
    String pub_path;
    String private_path;
    Multipart m;

    private SecretKey CreateSecretKey() throws NoSuchAlgorithmException, FileNotFoundException, IOException {
        SecretKey secret = null;
        KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
        secret = keygenerator.generateKey();

        FileOutputStream fout = null;
        fout = new FileOutputStream("secret");
        fout.write(secret.getEncoded());
        fout.close();

        return secret;
    }

    public byte[] EncryptSymmetric(String data, String sck_path) throws NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException {

        try {
            //Reading secretkey from file
            DataInputStream dis = new DataInputStream(new FileInputStream(sck_path));
            byte[] buff = new byte[dis.available()];
            dis.readFully(buff);
            dis.close();
            DESKeySpec ks = new DESKeySpec(buff);
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            SecretKey myDesKey = skf.generateSecret(ks);

            Cipher desCipher;
            // Create the cipher 
            desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            byte[] text = data.getBytes();
            try {
                desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
                byte[] result = desCipher.doFinal(text);
                return result;
                // System.out.println(textEncrypted);

            } catch (Exception ex) {
                ex.printStackTrace();
            }



        } catch (IOException ex) {
            Logger.getLogger(project_1.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(project_1.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public byte[] DecryptSymmetric(byte[] data, String sck_path) {
        try {
            //byte[] data = _data.getBytes();   
            DataInputStream dis = new DataInputStream(new FileInputStream(sck_path));
            byte[] buff = new byte[dis.available()];
            dis.readFully(buff);
            dis.close();

            DESKeySpec ds = new DESKeySpec(buff);
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            SecretKey desKey = skf.generateSecret(ds);

            Cipher decypher;
            decypher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            decypher.init(Cipher.DECRYPT_MODE, desKey);
            byte[] result = decypher.doFinal(data);
            String result1 = new String(result);

            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    private KeyPair LoadKeyPair() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        //Load public
        File pf = new File("pub");
        byte[] s = new byte[(int) pf.length()];
        FileInputStream fin = new FileInputStream(pf);
        fin.read(s);
        fin.close();
        //Load private
        File pvf = new File("prv");
        byte[] ss = new byte[(int) pvf.length()];
        FileInputStream fin1 = new FileInputStream(pvf);
        fin1.read(ss);
        fin1.close();

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(s);
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(ss);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

        return new KeyPair(publicKey, privateKey);
    }

    private KeyPair LoadKeyPairX() throws Exception {

        //Load public
        File pf = new File("pubs");
        byte[] s = new byte[(int) pf.length()];
        FileInputStream fin = new FileInputStream(pf);
        fin.read(s);
        fin.close();
        //Load private
        File pvf = new File("prvs");
        byte[] ss = new byte[(int) pvf.length()];
        FileInputStream fin1 = new FileInputStream(pvf);
        fin1.read(ss);
        fin1.close();

        KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(s);
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(ss);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

        return new KeyPair(publicKey, privateKey);
    }

    public project_1() {
        initComponents();
        this.login_frame.setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        login_frame = new javax.swing.JFrame();
        jPanel3 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        email = new javax.swing.JTextField();
        passwd = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();
        error_passwd_email = new javax.swing.JLabel();
        ComposeMail_frame = new javax.swing.JFrame();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        content_mail_compose = new javax.swing.JTextPane();
        To_Address_compose = new javax.swing.JTextField();
        Subject_compose = new javax.swing.JTextField();
        bt_send = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        cbo_encryptType = new javax.swing.JComboBox();
        ckb_sign = new javax.swing.JCheckBox();
        bt_generate = new javax.swing.JButton();
        bt_generateKeyPair = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        bt_importSecretKey = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();
        bt_importPublicKey = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();
        bt_importPrivateKey = new javax.swing.JButton();
        read_mail_frame = new javax.swing.JFrame();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        content_readmail = new javax.swing.JTextPane();
        from_addr_readmail = new javax.swing.JTextField();
        subject_readmail = new javax.swing.JTextField();
        delete_mail_frame = new javax.swing.JFrame();
        jLabel8 = new javax.swing.JLabel();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        key_enter = new javax.swing.JFrame();
        key_choose = new javax.swing.JFileChooser();
        key_enter2 = new javax.swing.JFrame();
        key_choose1 = new javax.swing.JFileChooser();
        key_enter3 = new javax.swing.JFrame();
        key_choose2 = new javax.swing.JFileChooser();
        key_enter4 = new javax.swing.JFrame();
        key_choose3 = new javax.swing.JFileChooser();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        bt_mailbox = new javax.swing.JButton();
        bt_delete = new javax.swing.JButton();
        bt_compose = new javax.swing.JButton();
        bt_readmail = new javax.swing.JButton();
        lb_email = new javax.swing.JLabel();

        login_frame.setTitle("Login");
        login_frame.setBounds(new java.awt.Rectangle(100, 100, 380, 210));

        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(0, 0, 153));
        jLabel3.setText("                    ĐĂNG NHẬP GMAIL");

        jLabel1.setText("Email:");

        jLabel2.setText("Password:");

        jButton4.setText("Đăng nhập");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        error_passwd_email.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        error_passwd_email.setForeground(new java.awt.Color(204, 0, 0));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(error_passwd_email, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton4))
                            .addComponent(email)
                            .addComponent(passwd)))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(82, 82, 82)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 75, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(passwd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton4)
                    .addComponent(error_passwd_email, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(41, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout login_frameLayout = new javax.swing.GroupLayout(login_frame.getContentPane());
        login_frame.getContentPane().setLayout(login_frameLayout);
        login_frameLayout.setHorizontalGroup(
            login_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(login_frameLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        login_frameLayout.setVerticalGroup(
            login_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(login_frameLayout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        ComposeMail_frame.setTitle("Compose Mail");
        ComposeMail_frame.setBounds(new java.awt.Rectangle(200, 100, 800, 600));

        jLabel4.setText("To:");

        jLabel5.setText("Subject:");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Content"));

        jScrollPane2.setViewportView(content_mail_compose);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE)
        );

        bt_send.setText("Send");
        bt_send.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_sendActionPerformed(evt);
            }
        });

        jLabel9.setText("EncryptType:");

        cbo_encryptType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "None", "Symmetric only", "Symmetric & Asymmetric" }));
        cbo_encryptType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbo_encryptTypeActionPerformed(evt);
            }
        });

        ckb_sign.setText("Signature");

        bt_generate.setText("Generate KeyPair");
        bt_generate.setEnabled(false);
        bt_generate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_generateActionPerformed(evt);
            }
        });

        bt_generateKeyPair.setText("Generate");
        bt_generateKeyPair.setEnabled(false);
        bt_generateKeyPair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_generateKeyPairActionPerformed(evt);
            }
        });

        jLabel10.setText("Secretkey:");

        bt_importSecretKey.setText("Import");
        bt_importSecretKey.setEnabled(false);
        bt_importSecretKey.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_importSecretKeyActionPerformed(evt);
            }
        });

        jLabel11.setText("PublicKey:");

        bt_importPublicKey.setText("Import");
        bt_importPublicKey.setEnabled(false);
        bt_importPublicKey.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_importPublicKeyActionPerformed(evt);
            }
        });

        jLabel12.setText("PrivateKey:");

        bt_importPrivateKey.setText("Import");
        bt_importPrivateKey.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_importPrivateKeyActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ComposeMail_frameLayout = new javax.swing.GroupLayout(ComposeMail_frame.getContentPane());
        ComposeMail_frame.getContentPane().setLayout(ComposeMail_frameLayout);
        ComposeMail_frameLayout.setHorizontalGroup(
            ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ComposeMail_frameLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(ComposeMail_frameLayout.createSequentialGroup()
                        .addGroup(ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(To_Address_compose)
                            .addComponent(Subject_compose)))
                    .addGroup(ComposeMail_frameLayout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel9)
                            .addComponent(jLabel10))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(ComposeMail_frameLayout.createSequentialGroup()
                                .addComponent(bt_generateKeyPair, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bt_importSecretKey))
                            .addComponent(cbo_encryptType, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(55, 55, 55)
                        .addGroup(ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(ComposeMail_frameLayout.createSequentialGroup()
                                .addComponent(jLabel11)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(bt_importPublicKey))
                            .addComponent(bt_generate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                        .addGroup(ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(ckb_sign)
                            .addGroup(ComposeMail_frameLayout.createSequentialGroup()
                                .addComponent(jLabel12)
                                .addGap(18, 18, 18)
                                .addComponent(bt_importPrivateKey)))
                        .addGap(125, 125, 125)
                        .addComponent(bt_send, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        ComposeMail_frameLayout.setVerticalGroup(
            ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ComposeMail_frameLayout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(To_Address_compose, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(Subject_compose, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(ComposeMail_frameLayout.createSequentialGroup()
                        .addGroup(ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(bt_generateKeyPair)
                            .addComponent(jLabel10)
                            .addComponent(bt_importSecretKey)
                            .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(bt_importPublicKey)
                            .addComponent(jLabel12)
                            .addComponent(bt_importPrivateKey))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                        .addGroup(ComposeMail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel9)
                            .addComponent(bt_generate)
                            .addComponent(cbo_encryptType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(ckb_sign)))
                    .addComponent(bt_send, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        read_mail_frame.setTitle("Read Mail");
        read_mail_frame.setBounds(new java.awt.Rectangle(200, 100, 400, 400));

        jLabel6.setText("From Address:");

        jLabel7.setText("Subject:");

        content_readmail.setBorder(javax.swing.BorderFactory.createTitledBorder("Content"));
        jScrollPane3.setViewportView(content_readmail);

        javax.swing.GroupLayout read_mail_frameLayout = new javax.swing.GroupLayout(read_mail_frame.getContentPane());
        read_mail_frame.getContentPane().setLayout(read_mail_frameLayout);
        read_mail_frameLayout.setHorizontalGroup(
            read_mail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(read_mail_frameLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(read_mail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3)
                    .addGroup(read_mail_frameLayout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(from_addr_readmail, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE))
                    .addGroup(read_mail_frameLayout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(subject_readmail)))
                .addContainerGap())
        );
        read_mail_frameLayout.setVerticalGroup(
            read_mail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(read_mail_frameLayout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(read_mail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(from_addr_readmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(read_mail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(subject_readmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
                .addContainerGap())
        );

        delete_mail_frame.setTitle("Delete Mail");
        delete_mail_frame.setBounds(new java.awt.Rectangle(300, 100, 250, 140));

        jLabel8.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N
        jLabel8.setForeground(new java.awt.Color(255, 0, 0));
        jLabel8.setText("BẠN XÓA MAIL THEO HÌNH THỨC NÀO");

        jButton7.setText("Client");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jButton8.setText("Server");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout delete_mail_frameLayout = new javax.swing.GroupLayout(delete_mail_frame.getContentPane());
        delete_mail_frame.getContentPane().setLayout(delete_mail_frameLayout);
        delete_mail_frameLayout.setHorizontalGroup(
            delete_mail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(delete_mail_frameLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(delete_mail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel8)
                    .addGroup(delete_mail_frameLayout.createSequentialGroup()
                        .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(13, Short.MAX_VALUE))
        );
        delete_mail_frameLayout.setVerticalGroup(
            delete_mail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(delete_mail_frameLayout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jLabel8)
                .addGap(18, 18, 18)
                .addGroup(delete_mail_frameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton7, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)
                    .addComponent(jButton8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(23, 23, 23))
        );

        key_enter.setBounds(new java.awt.Rectangle(0, 0, 600, 400));

        key_choose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                key_chooseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout key_enterLayout = new javax.swing.GroupLayout(key_enter.getContentPane());
        key_enter.getContentPane().setLayout(key_enterLayout);
        key_enterLayout.setHorizontalGroup(
            key_enterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, key_enterLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(key_choose, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
                .addContainerGap())
        );
        key_enterLayout.setVerticalGroup(
            key_enterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, key_enterLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(key_choose, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE)
                .addContainerGap())
        );

        key_enter2.setBounds(new java.awt.Rectangle(0, 0, 600, 400));

        key_choose1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                key_choose1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout key_enter2Layout = new javax.swing.GroupLayout(key_enter2.getContentPane());
        key_enter2.getContentPane().setLayout(key_enter2Layout);
        key_enter2Layout.setHorizontalGroup(
            key_enter2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, key_enter2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(key_choose1, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
                .addContainerGap())
        );
        key_enter2Layout.setVerticalGroup(
            key_enter2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, key_enter2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(key_choose1, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE)
                .addContainerGap())
        );

        key_enter3.setBounds(new java.awt.Rectangle(0, 0, 600, 400));

        key_choose2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                key_choose2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout key_enter3Layout = new javax.swing.GroupLayout(key_enter3.getContentPane());
        key_enter3.getContentPane().setLayout(key_enter3Layout);
        key_enter3Layout.setHorizontalGroup(
            key_enter3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, key_enter3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(key_choose2, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
                .addContainerGap())
        );
        key_enter3Layout.setVerticalGroup(
            key_enter3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, key_enter3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(key_choose2, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE)
                .addContainerGap())
        );

        key_enter4.setBounds(new java.awt.Rectangle(0, 0, 600, 400));

        key_choose3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                key_choose3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout key_enter4Layout = new javax.swing.GroupLayout(key_enter4.getContentPane());
        key_enter4.getContentPane().setLayout(key_enter4Layout);
        key_enter4Layout.setHorizontalGroup(
            key_enter4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, key_enter4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(key_choose3, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
                .addContainerGap())
        );
        key_enter4Layout.setVerticalGroup(
            key_enter4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, key_enter4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(key_choose3, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE)
                .addContainerGap())
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Securety Mail");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "GMAIL", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 12), new java.awt.Color(0, 0, 204))); // NOI18N

        bt_mailbox.setText("Mail Inbox");
        bt_mailbox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_mailboxActionPerformed(evt);
            }
        });

        bt_delete.setText("Delete Mail");
        bt_delete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_deleteActionPerformed(evt);
            }
        });

        bt_compose.setText("Compose Mail");
        bt_compose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_composeActionPerformed(evt);
            }
        });

        bt_readmail.setText("Read Mail");
        bt_readmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_readmailActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(bt_compose, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE)
            .addComponent(bt_delete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(bt_mailbox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(bt_readmail, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(bt_mailbox, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(4, 4, 4)
                .addComponent(bt_readmail, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bt_delete, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bt_compose, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(210, Short.MAX_VALUE))
        );

        lb_email.setFont(new java.awt.Font("Times New Roman", 3, 14)); // NOI18N
        lb_email.setForeground(new java.awt.Color(255, 0, 0));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lb_email, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lb_email, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseClicked

    private void bt_composeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_composeActionPerformed
        // TODO add your handling code here:
        this.ComposeMail_frame.setVisible(true);
    }//GEN-LAST:event_bt_composeActionPerformed
    public Properties props = System.getProperties();
    public Session session;
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        try {
            // TODO add your handling code here:

            // Properties props = System.getProperties();
            props.setProperty("mail.store.protocol", "imaps");
            this.session = Session.getDefaultInstance(props, null);
            Store store = session.getStore("imaps");
            try {
                store.connect("imap.gmail.com", this.email.getText(), this.passwd.getText());
                this.login_frame.setVisible(false);
                this.Rev_Mail();
                this.lb_email.setText(this.email.getText());
                this.setVisible(true);
            } catch (IOException ex) {
                Logger.getLogger(project_1.class.getName()).log(Level.SEVERE, null, ex);
            } catch (MessagingException ex) {
                this.error_passwd_email.setText("Email hoặc Password không đúng");
            }
        } catch (Exception ex) {
            Logger.getLogger(project_1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void bt_mailboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_mailboxActionPerformed
        try {
            // TODO add your handling code here:
            this.Rev_Mail();
        } catch (IOException ex) {
        }
    }//GEN-LAST:event_bt_mailboxActionPerformed

    private void bt_sendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_sendActionPerformed
        try {
            // TODO add your handling code here:
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.port", "587");
            final String username = this.email.getText();
            final String password = this.passwd.getText();
            Session session2 = Session.getInstance(props,
                    new javax.mail.Authenticator() {

                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username, password);
                        }
                    });
            Message message2 = new MimeMessage(session2);


            message2.setFrom(new InternetAddress(this.email.getText()));
            message2.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(this.To_Address_compose.getText()));
            message2.setSubject(this.Subject_compose.getText());
            Multipart multipart = new MimeMultipart();



            BodyPart _title = new MimeBodyPart();

            BodyPart _content = new MimeBodyPart();
            BodyPart _key = new MimeBodyPart();
            BodyPart _sign = new MimeBodyPart();
            boolean flag = this.ckb_sign.isSelected();
            String content = this.content_mail_compose.getText();
            switch (cbo_encryptType.getSelectedItem().toString()) {
                case "None":
                    _title.setText("nothing");
                    _content.setText(content);
                    _key.setText("");
                    _sign.setText("");
                    break;
                case "Symmetric only":
                    if (flag == false) //sym not sign
                    {
                        _title.setText("sym");

                        if (keyPath != "") {
                            byte[] b = this.EncryptSymmetric(content, keyPath);

                            //Make ecrypted file
                            FileOutputStream fos = new FileOutputStream("ecrypted");
                            fos.write(b);
                            fos.close();
                            DataSource ds = new FileDataSource("ecrypted");
                            //Add attachment    
                            _content.setDataHandler(new DataHandler(ds));
                            _content.setFileName("dataEcrypted");
                            _key.setText("");
                            _sign.setText("");
                        } else {
                            //No keypath, send raw
                            _title.setText("nothing");
                            _content.setText(content);
                            _key.setText("");
                            _sign.setText("");
                        }
                    } else //sym with sign
                    {
                        //binh thuong
                        _title.setText("syms");
                        SecretKey sc = this.CreateSecretKey();
                        byte[] b = this.EncryptSymmetric(content, "secret");

                        //Make ecrypted file
                        FileOutputStream fos = new FileOutputStream("ecrypted");
                        fos.write(b);
                        fos.close();


                        DataSource ds = new FileDataSource("ecrypted");

                        //Add attachment    
                        _content.setDataHandler(new DataHandler(ds));
                        _content.setFileName("dataEcrypted");
                        //Xong data

                        //tao cap key pair
                        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
                        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");

                        keyGen.initialize(1024);

                        KeyPair pair = keyGen.generateKeyPair();
                        PrivateKey priv = pair.getPrivate();
                        PublicKey pub = pair.getPublic();

                        FileOutputStream f = new FileOutputStream("prvsign");
                        f.write(priv.getEncoded());
                        f.close();

                        FileOutputStream g = new FileOutputStream("pubsign");
                        g.write(pub.getEncoded());
                        g.close();;

                        DataSource y = new FileDataSource("pubsign");
                        _key.setDataHandler(new DataHandler(y));
                        _key.setFileName("pubsign");
                        //Gan them chu ki
                        Signature dsa;
                        try {
                            dsa = Signature.getInstance("SHA1withDSA", "SUN");
                            dsa.initSign(priv);
                            FileInputStream fis = new FileInputStream("ecrypted");
                            BufferedInputStream bufin = new BufferedInputStream(fis);
                            byte[] buffer = new byte[1024];
                            int len;
                            while (bufin.available() != 0) {
                                len = bufin.read(buffer);
                                dsa.update(buffer, 0, len);
                            };

                            bufin.close();
                            //Real sign
                            byte[] realSig = dsa.sign();
                            /*
                             * Save the signature in a file
                             */
                            FileOutputStream sigfos = new FileOutputStream("sig");
                            sigfos.write(realSig);

                            sigfos.close();
                            DataSource dss = new FileDataSource("sig");

                            //Add attachment    
                            _sign.setDataHandler(new DataHandler(dss));
                            _sign.setFileName("sig");


                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    break;
                default://asym encrypt
                {
                    //SymmetricEncrypt first=>secretkey;
                    _title.setText("asym");
                    if (flag == false) {
                        SecretKey secret = this.CreateSecretKey();
                        byte[] scrk = secret.getEncoded();
                        //EncryptData
                        byte[] encryptData = this.EncryptSymmetric(content, "secret");
                        FileOutputStream fos = new FileOutputStream("pck");
                        fos.write(encryptData);
                        fos.close();
                        DataSource ds = new FileDataSource("pck");
                        _content.setDataHandler(new DataHandler(ds));
                        _content.setFileName("encrypt_data");
                        /*
                         * KeyPair keyPair = this.LoadKeyPair(); PublicKey pub =
                         * keyPair.getPublic(); PrivateKey pri =
                         * keyPair.getPrivate();
                         */
                        //Load publicKey
                        File pf = new File(pub_path);
                        byte[] s = new byte[(int) pf.length()];
                        FileInputStream fin = new FileInputStream(pf);
                        fin.read(s);
                        fin.close();


                        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(s);
                        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

                        //Encrypt secret key
                        Cipher cipher;
                        cipher = Cipher.getInstance("RSA");
                        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
                        byte[] encryptSecretKey = cipher.doFinal(scrk);

                        FileOutputStream ffos = new FileOutputStream("pckec");
                        ffos.write(encryptSecretKey);
                        ffos.close();
                        DataSource ds1 = new FileDataSource("pckec");
                        _key.setDataHandler(new DataHandler(ds1));
                        _key.setFileName("encrypt_secretkey");
                        _sign.setText("");
                        break;
                    } else {
                        
                    }
                }


            }
            multipart.addBodyPart(_title);
            multipart.addBodyPart(_content);
            multipart.addBodyPart(_key);
            multipart.addBodyPart(_sign);
            message2.setContent(multipart);

            Transport.send(message2);
            System.out.println("done");
            this.ComposeMail_frame.setVisible(false);

        } catch (Exception ex) {
            Logger.getLogger(project_1.class.getName()).log(Level.SEVERE, null, ex);
        }


    }//GEN-LAST:event_bt_sendActionPerformed

    private void bt_readmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_readmailActionPerformed
        try {
            // TODO add your handling code here:
            int i;
            i = this.jTable1.getSelectedRow();
            Message msg;
            msg = messages[i];
            String addr_from = InternetAddress.toString(msg.getFrom());
            String _subject = msg.getSubject();
            this.from_addr_readmail.setText(addr_from);
            this.subject_readmail.setText(_subject);
            this.read_mail_frame.setVisible(true);
            if (msg.getContent() instanceof Multipart) {
                _subject = msg.getSubject().toString();
                Multipart multipart = (Multipart) msg.getContent();
                m = multipart;
                int len = multipart.getCount();

                //print content
                BodyPart title = multipart.getBodyPart(0);
                switch (title.getContent().toString()) {
                    case "nothing":
                        //Hien thi nhung phan noi dung
                        this.content_readmail.setText(multipart.getBodyPart(1).getContent().toString());
                        break;
                    case "sym":
                        //Lay attachment
                        this.key_enter2.setTitle("Encrypted mail!Please choose secret key!!!");
                        this.key_enter2.setVisible(true);


                        break;
                    case "syms": {
                        Part vsign = multipart.getBodyPart(3);//sign
                        String disposition = vsign.getDisposition();
                        //Check cho vui
                        if (disposition.equals("ATTACHMENT")) {
                            InputStream inf = vsign.getInputStream();
                            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                            int nRead;
                            byte[] data = new byte[10000];
                            while ((nRead = inf.read(data, 0, data.length)) != -1) {
                                buffer.write(data, 0, nRead);
                            }
                            buffer.flush();
                            byte[] s = buffer.toByteArray();
                            //s = signToVerify

                            //test
                            FileOutputStream bb = new FileOutputStream("sign_recv");
                            bb.write(s);
                            bb.close();
                            System.out.println("Sign " + new String(s));


                            //read public key

                            Part Key = multipart.getBodyPart(2);//sign
                            InputStream ii = Key.getInputStream();
                            byte[] n;
                            ByteArrayOutputStream buff3 = new ByteArrayOutputStream();
                            int iRead;
                            byte[] dat = new byte[10000];
                            while ((iRead = ii.read(dat, 0, dat.length)) != -1) {
                                buff3.write(dat, 0, iRead);
                            }
                            buff3.flush();
                            n = buff3.toByteArray();

                            FileOutputStream bbb = new FileOutputStream("pub_recv");
                            bbb.write(n);
                            bbb.close();

                            X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(n);

                            KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
                            PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

                            System.err.println(pubKey.getEncoded());


                            Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
                            sig.initVerify(pubKey);

                            Part datax = multipart.getBodyPart(1);
                            InputStream is = datax.getInputStream();
                            ByteArrayOutputStream bf = new ByteArrayOutputStream();
                            int Read;
                            byte[] dt = new byte[10000];
                            while ((Read = is.read(dt, 0, dt.length)) != -1) {
                                bf.write(dt, 0, Read);
                            }
                            bf.flush();
                            byte[] h = bf.toByteArray(); //content

                            sig.update(h);

                            boolean verify = sig.verify(s);
                            System.out.println(verify);
                            if (verify == true) {
                                this.key_enter2.setTitle("Encrypted mail!Please choose secret key!!!");
                                this.key_enter2.setVisible(true);
                            }

                        }
                        break;
                    }
                    case "asym": {
                        //Mesage has tittle ,2 attach: 1content-1key
                        Part key = multipart.getBodyPart(2);
                        String disposition = key.getDisposition();
                        byte[] s;
                        //Check cho vui
                        if (disposition.equals("ATTACHMENT")) {
                            InputStream inf = key.getInputStream();
                            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                            int nRead;
                            byte[] data = new byte[10000];
                            while ((nRead = inf.read(data, 0, data.length)) != -1) {
                                buffer.write(data, 0, nRead);
                            }
                            buffer.flush();
                            s = buffer.toByteArray();

                            //Load private key
                            if (private_path.equals("")) {
                                private_path = "prv";
                            }
                            File pf = new File(private_path);
                            byte[] temp = new byte[(int) pf.length()];
                            FileInputStream fin = new FileInputStream(pf);
                            fin.read(temp);
                            fin.close();
                            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(temp);
                            PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

                            Cipher cipher;
                            cipher = Cipher.getInstance("RSA");
                            cipher.init(Cipher.DECRYPT_MODE, privateKey);
                            byte[] secret = cipher.doFinal(s);
                            //Yes, I has secretkey
                            System.out.println("secretkey: " + new String(secret));
                            DESKeySpec ds = new DESKeySpec(secret);
                            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
                            SecretKey secretKey = skf.generateSecret(ds);



                            //Decrypt mail
                            Part content = multipart.getBodyPart(1);
                            String disposition2 = content.getDisposition();
                            byte[] x;
                            //Check cho vui
                            if (disposition.equals("ATTACHMENT")) {
                                InputStream inf2 = content.getInputStream();
                                ByteArrayOutputStream buffer2 = new ByteArrayOutputStream();
                                int nRead2;
                                byte[] data2 = new byte[10000];
                                while ((nRead2 = inf2.read(data2, 0, data2.length)) != -1) {
                                    buffer2.write(data2, 0, nRead2);
                                }
                                buffer2.flush();
                                x = buffer2.toByteArray();
                                //Yes, I has mail content.
                                Cipher decypher;
                                decypher = Cipher.getInstance("DES/ECB/PKCS5Padding");
                                decypher.init(Cipher.DECRYPT_MODE, secretKey);
                                byte[] result = decypher.doFinal(x);
                                String result1 = new String(result);
                                System.out.println(result1);
                                this.content_readmail.setText(result1);
                            }
                            break;
                        }
                    }
                    default:
                    //Hien thi tat ca bodypart
                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }//GEN-LAST:event_bt_readmailActionPerformed

    private void bt_deleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_deleteActionPerformed
        // TODO add your handling code here:
        this.delete_mail_frame.setVisible(true);
    }//GEN-LAST:event_bt_deleteActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        try {
            // TODO add your handling code here:
            int i = this.jTable1.getSelectedRow();
            Message msg = this.messages[i];
            msg.setFlag(Flag.SEEN, true);
            this.Rev_Mail();
            this.delete_mail_frame.setVisible(false);
        } catch (IOException | MessagingException ex) {
            Logger.getLogger(project_1.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_jButton7ActionPerformed

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
        try {
            // TODO add your handling code here:
            int i = this.jTable1.getSelectedRow();
            this.messages[i].setFlag(Flag.DELETED, true);
            this.Rev_Mail();
            this.delete_mail_frame.setVisible(false);
        } catch (IOException | MessagingException ex) {
            Logger.getLogger(project_1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton8ActionPerformed

    private void cbo_encryptTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbo_encryptTypeActionPerformed
        // TODO add your handling code here:
        if (this.cbo_encryptType.getSelectedItem().toString().equals("Symmetric only")) {
            this.bt_generate.setEnabled(false);
            this.bt_generateKeyPair.setEnabled(true);
            this.bt_importSecretKey.setEnabled(true);
            this.bt_importPublicKey.setEnabled(false);
        } else if (this.cbo_encryptType.getSelectedItem().toString().equals("Symmetric & Asymmetric")) {
            this.bt_generate.setEnabled(true);
            this.bt_generateKeyPair.setEnabled(false);
            this.bt_importSecretKey.setEnabled(false);
            this.bt_importPublicKey.setEnabled(true);
        } else//None
        {
            this.bt_generate.setEnabled(false);
            this.bt_generateKeyPair.setEnabled(false);
            this.bt_importSecretKey.setEnabled(false);
            this.bt_importPublicKey.setEnabled(false);
        }
    }//GEN-LAST:event_cbo_encryptTypeActionPerformed

    private void bt_generateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_generateActionPerformed
        try {
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(1024);
            KeyPair keypair = keyGen.generateKeyPair();
            PublicKey pub = keypair.getPublic();
            PrivateKey prv = keypair.getPrivate();
            //Store public key
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
                    pub.getEncoded());
            FileOutputStream fos = new FileOutputStream("pub");
            fos.write(x509EncodedKeySpec.getEncoded());
            fos.close();

            // Store Private Key.
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                    prv.getEncoded());
            fos = new FileOutputStream("prv");
            fos.write(pkcs8EncodedKeySpec.getEncoded());
            fos.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_bt_generateActionPerformed

    private void key_chooseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_key_chooseActionPerformed
        keyPath = this.key_choose.getSelectedFile().getPath();
        this.key_enter.setTitle("Locate your secret key");
        this.key_choose.setCurrentDirectory(new File(System.getProperty("user.home")));
        this.key_choose.setSelectedFile(null);
        this.key_enter.setVisible(false);
    }//GEN-LAST:event_key_chooseActionPerformed

    private void bt_generateKeyPairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_generateKeyPairActionPerformed
        try {
            // TODO add your handling code here:
            this.CreateSecretKey();

        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(project_1.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(project_1.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(project_1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_bt_generateKeyPairActionPerformed

    private void key_choose1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_key_choose1ActionPerformed
        try {
            // TODO add your handling code here:
            keyPath = this.key_choose1.getSelectedFile().getPath();
            Part content_text = m.getBodyPart(1);
            String disposition = content_text.getDisposition();
            byte[] s;
            if (disposition.equals("ATTACHMENT")) {
                InputStream inf = content_text.getInputStream();
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                int nRead;
                byte[] data = new byte[10000];
                while ((nRead = inf.read(data, 0, data.length)) != -1) {
                    buffer.write(data, 0, nRead);
                }
                buffer.flush();
                s = buffer.toByteArray();

                byte[] results = this.DecryptSymmetric(s, keyPath);
                String result = new String(results);
                System.out.println("After decrypt: " + result);
                this.content_readmail.setText(result + "\n");
            } else {
                //not handle
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            this.key_enter2.setVisible(false);
        }
    }//GEN-LAST:event_key_choose1ActionPerformed

    private void key_choose2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_key_choose2ActionPerformed
        // TODO add your handling code here:
        pub_path = this.key_choose2.getSelectedFile().getPath();
        this.key_enter3.setVisible(false);
    }//GEN-LAST:event_key_choose2ActionPerformed

    private void bt_importSecretKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_importSecretKeyActionPerformed
        // TODO add your handling code here:
        this.key_enter.setVisible(true);
    }//GEN-LAST:event_bt_importSecretKeyActionPerformed

    private void bt_importPublicKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_importPublicKeyActionPerformed
        // TODO add your handling code here:
        this.key_enter3.setVisible(true);
        this.key_enter3.setTitle("Insert the receiver's public key");
    }//GEN-LAST:event_bt_importPublicKeyActionPerformed

    private void key_choose3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_key_choose3ActionPerformed
        // TODO add your handling code here:
        private_path = this.key_choose3.getSelectedFile().getPath();
        this.key_enter4.setVisible(false);
    }//GEN-LAST:event_key_choose3ActionPerformed

    private void bt_importPrivateKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_importPrivateKeyActionPerformed
        // TODO add your handling code here:
        this.key_enter4.setTitle("Insert your private key!!!");
        this.key_enter4.setVisible(true);
    }//GEN-LAST:event_bt_importPrivateKeyActionPerformed
    
    
    public void Rev_Mail() throws IOException {
        this.jTable1.setModel(new javax.swing.table.DefaultTableModel(new Object[][]{}, new String[]{"From Address", "Subject", "Date"}));
        DefaultTableModel tm = (DefaultTableModel) this.jTable1.getModel();
        try {
            props.setProperty("mail.store.protocol", "imaps");
            this.session = Session.getDefaultInstance(props, null);
            Store store = session.getStore("imaps");
            store.connect("imap.gmail.com", this.email.getText(), this.passwd.getText());
            //System.out.println(store);
            Folder inbox = store.getFolder("Inbox");
            inbox.open(Folder.READ_WRITE);
            messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
            for (Message message : messages) {
                tm.addRow(new Object[]{InternetAddress.toString(message.getFrom()), message.getSubject(), message.getReceivedDate().toString()});
            }
        } catch (Exception e) {
            System.exit(1);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(project_1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(project_1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(project_1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(project_1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */


        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new project_1().setVisible(false);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFrame ComposeMail_frame;
    private javax.swing.JTextField Subject_compose;
    private javax.swing.JTextField To_Address_compose;
    private javax.swing.JButton bt_compose;
    private javax.swing.JButton bt_delete;
    private javax.swing.JButton bt_generate;
    private javax.swing.JButton bt_generateKeyPair;
    private javax.swing.JButton bt_importPrivateKey;
    private javax.swing.JButton bt_importPublicKey;
    private javax.swing.JButton bt_importSecretKey;
    private javax.swing.JButton bt_mailbox;
    private javax.swing.JButton bt_readmail;
    private javax.swing.JButton bt_send;
    private javax.swing.JComboBox cbo_encryptType;
    private javax.swing.JCheckBox ckb_sign;
    private javax.swing.JTextPane content_mail_compose;
    private javax.swing.JTextPane content_readmail;
    private javax.swing.JFrame delete_mail_frame;
    private javax.swing.JTextField email;
    private javax.swing.JLabel error_passwd_email;
    private javax.swing.JTextField from_addr_readmail;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JFileChooser key_choose;
    private javax.swing.JFileChooser key_choose1;
    private javax.swing.JFileChooser key_choose2;
    private javax.swing.JFileChooser key_choose3;
    private javax.swing.JFrame key_enter;
    private javax.swing.JFrame key_enter2;
    private javax.swing.JFrame key_enter3;
    private javax.swing.JFrame key_enter4;
    private javax.swing.JLabel lb_email;
    private javax.swing.JFrame login_frame;
    private javax.swing.JPasswordField passwd;
    private javax.swing.JFrame read_mail_frame;
    private javax.swing.JTextField subject_readmail;
    // End of variables declaration//GEN-END:variables
}
